package cn.jjxx.modules.sso.service.impl;

import java.io.Serializable;

import cn.jjxx.modules.sys.security.shiro.realm.UserRealm.Principal;
import cn.jjxx.modules.sys.security.shiro.web.filter.authc.UsernamePasswordToken;
import cn.jjxx.modules.sys.utils.UserUtils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.framework.customutil.endecryption.rsa.RSAHelper;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.modules.sso.entity.SSOLoginInfo;
import cn.jjxx.modules.sso.service.ISSOClientService;
import cn.jjxx.modules.sso.utils.EnDecryptUtils;
import cn.jjxx.modules.sso.utils.EnDecryptUtils.EnDecryptType;

@Service
public class SSOClientService implements ISSOClientService{
	
	private static final String SSO_SECURET_KEY = "sso.secret.key"; 
	private static final String SSO_SECURET_TYPE = "sso.secret.type";

	@Override
	public String login(String jsonpCallback, String encryptParams){
		JSONObject json = new JSONObject();
		String url = null;
        try {
        	//创建subject实例
            Subject subject = SecurityUtils.getSubject();
            //secretKey 为秘钥，根据项目设置秘钥（AES/BASE64/DES公钥和私钥是一致的，RSA的公钥和私钥是不一样的）
            String secretKey = MessageUtils.getMessage(SSO_SECURET_KEY);
            String secretType = MessageUtils.getMessage(SSO_SECURET_TYPE);
            EnDecryptType enDecryptType = EnDecryptUtils.getEnDecryptType(secretType);
            //String secretKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRGxshehkxbQKziDJy2F81nBaX4ek+o80PJMaGMEOhRixbbfX55jUA50fFW4NdzP/pyTilnt48PjkrrhvBFQ1OxD3LZbchBrlcICPkybu/RKFl+V5RMokZkbnpwy+Th13ItrjWNnGLLKGHRdWkOWtgALACr4idcbHmGW64XPIAZQIDAQAB";
            SSOLoginInfo info = EnDecryptUtils.decryptParams(encryptParams, enDecryptType, secretKey);
            String userId = info.getUserId();
        	Serializable sessionId = null;
        	Principal principal = UserUtils.getPrincipal();
        	if(ObjectUtils.isNullOrEmpty(principal)){
        		UsernamePasswordToken token = new UsernamePasswordToken(userId, false, "127.0.0.1", null, false, true);
        		subject.login(token);     
        		sessionId = subject.getSession().getId();
        	}else{
        		sessionId = principal.getSessionid();
        	}
        	System.out.println("sso单点登录："+sessionId);
        	url = info.getRedirectUrl();
        	json.put("ret", 0);
        	json.put("msg", "登录成功");
        	json.put("url", url);
        	json.put("sessionId", sessionId);
		} catch (Exception e) {
			json.put("ret", -1);
			json.put("msg", "登录异常");
		}
        //构造回调函数格式jsonpCallback(数据)
		return jsonpCallback+"('"+json.toJSONString()+"')";
	}
	
	@Override
	public AjaxJson login(String encryptParams){
		AjaxJson j = new AjaxJson();
		//创建subject实例
        try {
        	Subject subject = SecurityUtils.getSubject();
        	String secretKey = RSAHelper.getPrivateKey(RSAHelper.getKeyPair());
            SSOLoginInfo info = EnDecryptUtils.decryptParams(encryptParams, EnDecryptUtils.EnDecryptType.RSA, secretKey);
            String userId = info.getUserId();
        	Serializable sessionId = null;
        	Principal principal = UserUtils.getPrincipal();
        	if(ObjectUtils.isNullOrEmpty(principal)){
        		UsernamePasswordToken token = new UsernamePasswordToken(userId, false, "127.0.0.1", null, false, true);
        		subject.login(token);     
        		sessionId = subject.getSession().getId();
        	}else{
        		sessionId = principal.getSessionid();
        	}
        	System.out.println("sso单点登录："+sessionId);
    		j.setMsg("登录成功");
    		j.put("sessionId", sessionId);
		} catch (Exception e) {
			j.setRet(AjaxJson.RET_FAIL);
			j.setMsg("登录失败");
		}
		return j;
	}
	
	@Override
	public AjaxJson checkToken(){
		AjaxJson j = new AjaxJson();
		try {
			//创建subject实例
			Principal principal = UserUtils.getPrincipal();
			if(!ObjectUtils.isNullOrEmpty(principal)){
				Serializable sessionId = principal.getSessionid();
		        System.out.println("sso检测token:"+sessionId);
		        j.setMsg("验证成功");
	    		j.put("sessionId", sessionId);
			}else{
				j.setRet(AjaxJson.RET_FAIL);
				j.setMsg("验证失败,用户未登录");
			}
		} catch (Exception e) {
			j.setRet(AjaxJson.RET_FAIL);
			j.setMsg("验证异常");
		}
		return j;
	}
}
